//	Эта переменная говорит о том, что файл загружен браузером.
var resoLoaded = true;

//	Функция сигнализирует, что этот .js загрузился
var RESOPrice;
var RESOPriceDiscount;
var RESONotes = "";
var RESOInfo = {
	name: "РЕСО-Гарантия",
	price: 0,
	discountPrice: 0,
	notesToDisplay: new Array(0),
	notesSpecial: '',
	notes: "",
	rating: 0,
	realFr: 0,
	frArray: new Array(0),
	countSpecialNotes: 0,
	calc: function () {
		calculateRESO();
	}
};
var RESOXML = false;
//	Функция расчета стоимости КАСКО фирмы РЕСО
var RESONumErrors = 0;

function calculateRESO() {
	var k1, k2, k3, k4, k5, k6, k7, k8, k_right_helm, k_un, realFr;
	RESOPrice = 0;
	if (!RESOXML) $.ajax({
		url: "reso/RESO_cars.xml" + '?' + (rand % 1000),
		success: function (response) {
			RESOXML = response;
			calcRESO(RESOXML);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			RESONumErrors++;
			calculateRESO
		}
	});
	else calcRESO(RESOXML);
}

function calcRESO(response) {
	//		Ищем машину
	RESOInfo.notesToDisplay = new Array(0);
	RESOInfo.notesSpecial = '';
	var XML = $(response);
	var RESOXml = XML.find(city);
	//		alert(city+' |\n|'+XML.text());
	var kXml = XML.find("Ki:first");
	countSpecialNotes = 0;
	if (RESOXml.find("m>n").filter(function () {
		return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
	}).length != 0) {
		if (RESOXml.find("m>n").filter(function () {
			return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
		}).parent().find("cr>n").filter(function () {
			return $(this).text().toUpperCase() == carName.toUpperCase()
		}).length != 0) {
			carXML = RESOXml.find("m>n").filter(function () {
				return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
			}).parent().find("cr>n").filter(function () {
				return $(this).text().toUpperCase() == carName.toUpperCase()
			}).parent();
			//		alert("Ergo case0");
		} else if (RESOXml.find("m>n").filter(function () {
			return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
		}).parent().find("cr>n").filter(function () {
			return $(this).text() == "*"
		}).length != 0) {
			carXML = RESOXml.find("m>n").filter(function () {
				return $(this).text().toUpperCase() == manufacturerName.toUpperCase()
			}).parent().find("cr>n").filter(function () {
				return $(this).text() == "*"
			}).parent();
			//		alert("Ergo case1");
			//		alert("Ergo case1_    "+carXML.text());
		} else {
			carXML = RESOXml.find("m>n").filter(function () {
				return $(this).text() == "*"
			}).parent().find("cr>n").filter(function () {
				return $(this).text() == "*"
			}).parent();
			//alert("Ergo case2");
		}
	} else {
		carXML = RESOXml.find("m>n").filter(function () {
			return $(this).text() == "*"
		}).parent().find("cr>n").filter(function () {
			return $(this).text() == "*"
		}).parent();
	}
	var risk;
	var group = carXML.find('g').eq(0).text();
	//		базовый тариф ущерб
	var baseCost = 0;
	var currCar = carXML.find('a' + carAge.replace('carAge', '')).eq(0);
	if (group == '1') {
		var currCar = carXML.find('a' + carAge.replace('carAge', '')).eq(0);
		//		alert('currCar='+currCar.text());
		if (parseInt(price) < (parseInt(currCar.find('rss').eq(0).text()) * 1000)) {
			baseCost = parseInt(currCar.find('mbt').eq(0).text()) * 1000;
		} else {
			baseCost = parseInt(currCar.find('mbt').eq(0).text()) * 1000 + +(parseInt(price) - parseInt(currCar.find('rss').eq(0).text()) * 1000) * parseFloat(currCar.find('tdu').eq(0).text()) / 100;
		}
	} else {
		baseCost = parseInt(currCar.find('mbt').eq(0).text()) * 1000 + parseInt(price) * parseFloat(currCar.find('tdu').eq(0).text()) / 100;
		//			alert(	'mbt='+currCar.find('mbt').eq(0).text()+'\n'+'tdu='+currCar.find('tdu').eq(0).text()+'cc*tdu='+parseInt(price)*parseFloat(currCar.find('tdu').eq(0).text()));
		//		if(baseCost<parseInt(currCar.find('mbt').eq(0).text())*1000) baseCost=parseInt(currCar.find('mbt').eq(0).text())*1000;
	}


	//	Тариф хищение
	var kHish = parseFloat(currCar.find('th').eq(0).text()) / 100 * parseInt(price);

	//alert('carAge='+carAge);
	//alert('kCasco0='+carInfo.find('age>'+carAge).eq(0).text());
	var kCasco = parseFloat(carXML.find('a' + carAge.replace('carAge', '')).eq(0).text()) / 100;
	var fr;

	var kRassrochka;
	var kSto = 1;
	var kAgeExp;
	var kAgeExpMin = 0;
	var drAId, drEid;
	var selectedAlarm;
	if (multiDrive) kAgeExp = parseFloat(kXml.find('k_multiDrive').eq(0).text());
	else {
		var drA, drE;
		for (var i = 0; i < driversListForCalc.length; i++) {
			drA = parseInt(driversListForCalc.eq(i).find('.f-driver-c2').eq(0).find('input').eq(0).val());
			drE = parseInt(driversListForCalc.eq(i).find('.f-driver-c2').eq(0).find('input').eq(1).val());
			var maleSex = driversListForCalc.eq(i).find('.f-driver-c1').eq(0).find('a').eq(0).attr('class') == 'active';
			//				alert('maleSex='+maleSex);
			if (maleSex) maleSex = "male";
			else maleSex = "female";
			if (drA <= 22) drAId = 'less23';
			else if (drA <= 27) drAId = 'less28';
			else if (drA <= 36) drAId = 'less37';
			else if (drA <= 45) drAId = 'less46';
			else
			drAId = 'more45';
			if (drE < 1) drEid = 'less1';
			else if (drE < 2) drEid = 'less2';
			else
			drEid = 'more1';
			if (parseFloat(kXml.find(maleSex + ">" + drAId + '>' + drEid).text()) > kAgeExpMin) {
				kAgeExpMin = parseFloat(kXml.find(maleSex + ">" + drAId + '>' + drEid).text());
			}
		}
		kAgeExp = kAgeExpMin;
	}
	//		alert(kAgeExp);
	if (multiDrive) kAgeExp = 2;
	if ($('#corporatePerson').eq(0).attr('checked')) {
		if (rus) kAgeExp = 0.8;
		else kAgeExp = 1;
	}
	kRassrochka = $('input:checked').filter("[name='oplata']").get(0).value;
	if (kRassrochka == "2") RESOInfo.notesSpecial += 'В этой фирме нет предложения оплаты в 3 взноса.<br>';
	if (kRassrochka == "0") kRassrochka = 1;
	else if (kRassrochka == "1") kRassrochka = 1.03;
	else if (kRassrochka == "2") kRassrochka = 1.03;
	else if (kRassrochka == "3") kRassrochka = 1.05;

	//		Способ возмещения ущерба
	var selectedStoa = $('#f-2').find('input:checked').filter("[name='sto']").val();
	if (selectedStoa == '0') if ($('#guarantee').attr('checked')) kSto = 1;
	else
	kSto = 0.8;
	if (selectedStoa == '1') kSto = 1;
	if (selectedStoa == '3') kSto = 1.2;
	if (selectedStoa == '4') kSto = 1;
	fr = 1;
	realFr = 0;
	//	alert('selectedFr='+selectedFr+'g='+group);
	var frArr = new Array();
	if (group == '1') {
		frArr = [6000, 9000, 15000, 30000];
		if (selectedFr < 6000) {
			fr = 1;
			realFr = 0
		} else if (selectedFr < 9000) {
			fr = parseFloat(carXML.find('fr>c').eq(0).text());
			realFr = 6000
		} else if (selectedFr < 15000) {
			fr = parseFloat(carXML.find('fr>c').eq(1).text());
			realFr = 9000
		} else if (selectedFr < 30000) {
			fr = parseFloat(carXML.find('fr>c').eq(2).text());
			realFr = 15000
		} else if (selectedFr >= 30000) {
			fr = parseFloat(carXML.find('fr>c').eq(3).text());
			realFr = 30000
		}
	}
	if (group == '3') {
		if (selectedFr < 30000) {
			fr = 1;
			realFr = 0
		} else if (selectedFr < 45000) {
			fr = parseFloat(carXML.find('fr>c').eq(0).text());
			realFr = 30000
		} else if (selectedFr < 60000) {
			fr = parseFloat(carXML.find('fr>c').eq(1).text());
			realFr = 45000
		} else if (selectedFr < 90000) {
			fr = parseFloat(carXML.find('fr>c').eq(2).text());
			realFr = 60000
		} else if (selectedFr >= 90000) {
			fr = parseFloat(carXML.find('fr>c').eq(3).text());
			realFr = 90000
		}
		frArr = [30000, 45000, 60000, 90000];
	} else if (group == '2') {
		frArr = [6000, 9000, 15000, 30000];
		if (parseInt(price) < 450001) {
			if (selectedFr < 3000) {
				fr = 1;
				realFr = 0;
			} else if (selectedFr < 6000) {
				fr = 0.79;
				realFr = 3000
			} else if (selectedFr < 9000) {
				fr = 0.63;
				realFr = 6000
			} else if (selectedFr < 15000) {
				fr = 0.51;
				realFr = 9000
			} else if (selectedFr < 30000) {
				fr = 0.36;
				realFr = 15000
			} else if (selectedFr >= 30000) {
				fr = 0.25;
				realFr = 30000
			}
		} else if (parseInt(price) < 900001) {
			if (selectedFr < 3000) {
				fr = 1;
				realFr = 0;
			} else if (selectedFr < 6000) {
				fr = 0.88;
				realFr = 3000
			} else if (selectedFr < 9000) {
				fr = 0.76;
				realFr = 6000
			} else if (selectedFr < 15000) {
				fr = 0.66;
				realFr = 9000
			} else if (selectedFr < 30000) {
				fr = 0.51;
				realFr = 15000
			} else if (selectedFr >= 30000) {
				fr = 0.42;
				realFr = 30000
			}
		} else if (parseInt(price) < 1350001) {
			if (selectedFr < 3000) {
				fr = 1;
				realFr = 0;
			} else if (selectedFr < 6000) {
				fr = 0.9;
				realFr = 3000
			} else if (selectedFr < 9000) {
				fr = 0.8;
				realFr = 6000
			} else if (selectedFr < 15000) {
				fr = 0.71;
				realFr = 9000
			} else if (selectedFr < 30000) {
				fr = 0.58;
				realFr = 15000
			} else if (selectedFr >= 30000) {
				fr = 0.48;
				realFr = 30000
			}
		} else if (parseInt(price) < 2100001) {
			if (selectedFr < 3000) {
				fr = 1;
				realFr = 0;
			} else if (selectedFr < 6000) {
				fr = 0.93;
				realFr = 3000
			} else if (selectedFr < 9000) {
				fr = 0.87;
				realFr = 6000
			} else if (selectedFr < 15000) {
				fr = 0.81;
				realFr = 9000
			} else if (selectedFr < 30000) {
				fr = 0.70;
				realFr = 15000
			} else if (selectedFr >= 30000) {
				fr = 0.54;
				realFr = 30000
			}
		} else if (parseInt(price) < 3600001) {
			if (selectedFr < 3000) {
				fr = 1;
				realFr = 0;
			} else if (selectedFr < 6000) {
				fr = 0.96;
				realFr = 3000
			} else if (selectedFr < 9000) {
				fr = 0.92;
				realFr = 6000
			} else if (selectedFr < 15000) {
				fr = 0.88;
				realFr = 9000
			} else if (selectedFr < 30000) {
				fr = 0.81;
				realFr = 15000
			} else if (selectedFr >= 30000) {
				fr = 0.68;
				realFr = 30000
			}
		} else {
			if (selectedFr < 3000) {
				fr = 1;
				realFr = 0;
			} else if (selectedFr < 6000) {
				fr = 0.99;
				realFr = 3000
			} else if (selectedFr < 9000) {
				fr = 0.98;
				realFr = 6000
			} else if (selectedFr < 15000) {
				fr = 0.97;
				realFr = 9000
			} else if (selectedFr < 30000) {
				fr = 0.96;
				realFr = 15000
			} else if (selectedFr >= 30000) {
				fr = 0.95;
				realFr = 30000
			}
		}
	}


	//// Метки на линейке
	if (priceChanged) {
		RESOInfo.frArray = new Array(0);
		for (var i = 1; i <= frArr.length; i++) {
			var frImg = {
				value: null,
				image: null
			}
			if ((parseInt(price) / 100 * i) <= (slider2.maxVal + 1)) {
				try {
					frImg.value = frArr[i - 1];
					frImg.image = $("<img src='red.png' title='Франшиза " + addSpaces(frImg.value.toString()) + " руб. для страховой компании Ресо-Гарантия'>");
					RESOInfo.frArray.push(frImg);
				} catch (eee) {
					alert('err=' + eee)
				};
			}
		}
		for (var i = 0; i < RESOInfo.frArray.length; i++) {
			var fromLeft = parseInt(RESOInfo.frArray[i].value / slider2.maxVal * slider2.width);
			RESOInfo.frArray[i].image.css("position", "absolute").css("left", fromLeft + "px").css("top", "0px").click(function () {
				$(this).parent().click();
			}).focus(function () {
				$(this).blur()
			}).appendTo($("#barsliderDiv1").eq(0));
			RESOInfo.frArray[i].image.css("position", "absolute").css("left", fromLeft + "px").css("top", "0px").click(function () {
				$(this).parent().click();
			}).focus(function () {
				$(this).blur()
			}).clone().appendTo($("#barsliderDiv2").eq(0));
		}
	}

	//		окончательный расчет
	RESOInfo.price = parseInt((baseCost * kAgeExp * kSto * fr + kHish) * kRassrochka);
/*
alert(	"base="+baseCost+"\n"
+'group='+group
+"TDU=="+currCar.find('tdu').eq(0).text()+"\n"
+"kAgeExp="+kAgeExp+"\n"
+"kSto="+kSto+"\n"
+"kHish="+kHish+"\n"
+"currCar.find('th').eq(0).text()="+currCar.find('th').eq(0).text()+"\n"
+"kRassrochka="+kRassrochka+"\n"
+"fr="+fr+"\n"
);
*/
	currCar.find('th').eq(0).text();
	try {
		var discount = (100 - parseFloat($('#sk2').text())) / 100;
		RESOInfo.discountPrice = parseInt(RESOInfo.price * discount);
		RESOInfo.notes = RESONotes;
		RESOInfo.rating = 5;
		if (!realFr) realFr = 0;
		RESOInfo.realFr = realFr;
	} catch (eee) {
		//	alert(eee);
		counterCasco();
	}
	RESOInfo.notesSpecial += "Размер франшизы " + addSpaces(RESOInfo.realFr.toString()) + " руб.";
	RESOInfo.notesToDisplay.push("<span style='margin:0px; padding:0px; margin-left:24px;; position:relative; top:5px;'>Франшиза: " + addSpaces(RESOInfo.realFr.toString()) + " руб.</span><br>");
	RESOInfo.notesSpecial = 'Особенности расчета страховой компании РЕСО-Гарантия:<br>' + RESOInfo.notesSpecial;
	if (rus && (carAge == "carAge6" || carAge == "carAge7" || carAge == "carAge8")) {;
		//RESOInfo.notesSpecial='Отечественные ТС старше 5 лет принимаются только по согласованию с андеррайтером фирмы.<br>';
		//RESOInfo.notesToDisplay.push("<span style='margin:0px; padding:0px; margin-left:4px;; position:relative; top:-5px;'>Слишком старое ТС</span>br>");
	}
	//				counterCasco('reso');
	//	alert('reso carAge='+carAge);
	counterCasco();
}